<template>
  <div class="points-ledger">
    <div class="page-header">
      <h2>积分台账与统计分析</h2>
      <div class="header-actions">
        <el-button @click="exportReport('excel')">
          <el-icon><Download /></el-icon>
          导出Excel
        </el-button>
        <el-button @click="exportReport('pdf')">
          <el-icon><Document /></el-icon>
          导出PDF
        </el-button>
        <el-button @click="loadData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 统计概览 -->
    <div class="overview-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="card-content">
              <div class="card-icon total">
                <el-icon><Trophy /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-title">总记录数</div>
                <div class="card-value">{{ overview.totalRecords }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="card-content">
              <div class="card-icon add">
                <el-icon><Plus /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-title">总加分</div>
                <div class="card-value success">{{ overview.totalAddPoints }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="card-content">
              <div class="card-icon deduct">
                <el-icon><Minus /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-title">总扣分</div>
                <div class="card-value danger">{{ overview.totalDeductPoints }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="card-content">
              <div class="card-icon net">
                <el-icon><TrendCharts /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-title">净积分</div>
                <div class="card-value" :class="overview.netPoints >= 0 ? 'success' : 'danger'">
                  {{ overview.netPoints }}
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <el-tab-pane label="个人积分台账" name="personal">
        <div class="tab-content">
          <!-- 搜索筛选 -->
          <div class="search-form">
            <el-form :model="personalSearchForm" inline>
              <el-form-item label="员工">
                <el-select
                  v-model="personalSearchForm.userId"
                  placeholder="请选择员工"
                  clearable
                  filterable
                  remote
                  :remote-method="searchUsers"
                  :loading="userSearchLoading"
                >
                  <el-option
                    v-for="user in users"
                    :key="user.id"
                    :label="user.name"
                    :value="user.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="部门">
                <el-select v-model="personalSearchForm.departmentId" placeholder="请选择部门" clearable>
                  <el-option
                    v-for="dept in departments"
                    :key="dept.id"
                    :label="dept.name"
                    :value="dept.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="时间范围">
                <el-date-picker
                  v-model="personalSearchForm.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="loadPersonalData">
                  <el-icon><Search /></el-icon>
                  查询
                </el-button>
                <el-button @click="resetPersonalSearch">
                  <el-icon><Refresh /></el-icon>
                  重置
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 个人积分列表 -->
          <div class="table-container">
            <el-table
              v-loading="personalLoading"
              :data="personalList"
              stripe
              border
              style="width: 100%"
            >
              <el-table-column prop="userName" label="员工姓名" width="120" />
              <el-table-column prop="departmentName" label="部门" width="120" />
              <el-table-column prop="totalPoints" label="总积分" width="100">
                <template #default="{ row }">
                  <span :class="row.totalPoints >= 0 ? 'text-success' : 'text-danger'">
                    {{ row.totalPoints }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="addPoints" label="加分" width="100">
                <template #default="{ row }">
                  <span class="text-success">+{{ row.addPoints }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="deductPoints" label="扣分" width="100">
                <template #default="{ row }">
                  <span class="text-danger">-{{ row.deductPoints }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="recordCount" label="记录数" width="100" />
              <el-table-column prop="lastUpdateTime" label="最后更新时间" width="160" />
              <el-table-column label="操作" width="120" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="viewPersonalDetail(row)">
                    查看详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="personalPagination.page"
                v-model:page-size="personalPagination.pageSize"
                :total="personalPagination.total"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handlePersonalSizeChange"
                @current-change="handlePersonalCurrentChange"
              />
            </div>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="部门积分汇总" name="department">
        <div class="tab-content">
          <!-- 部门汇总列表 -->
          <div class="table-container">
            <el-table
              v-loading="departmentLoading"
              :data="departmentList"
              stripe
              border
              style="width: 100%"
            >
              <el-table-column prop="ranking" label="排名" width="80">
                <template #default="{ row }">
                  <el-tag v-if="row.ranking <= 3" :type="getRankingType(row.ranking)">
                    {{ row.ranking }}
                  </el-tag>
                  <span v-else>{{ row.ranking }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="departmentName" label="部门名称" width="150" />
              <el-table-column prop="totalPoints" label="总积分" width="100">
                <template #default="{ row }">
                  <span :class="row.totalPoints >= 0 ? 'text-success' : 'text-danger'">
                    {{ row.totalPoints }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="addPoints" label="总加分" width="100">
                <template #default="{ row }">
                  <span class="text-success">+{{ row.addPoints }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="deductPoints" label="总扣分" width="100">
                <template #default="{ row }">
                  <span class="text-danger">-{{ row.deductPoints }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="averagePoints" label="平均积分" width="100">
                <template #default="{ row }">
                  <span :class="row.averagePoints >= 0 ? 'text-success' : 'text-danger'">
                    {{ row.averagePoints.toFixed(1) }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="employeeCount" label="员工数" width="100" />
              <el-table-column prop="lastUpdateTime" label="最后更新时间" width="160" />
              <el-table-column label="操作" width="120" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="viewDepartmentDetail(row)">
                    查看详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-tab-pane>


      <el-tab-pane label="数据可视化" name="charts">
        <div class="tab-content">
          <!-- 图表区域 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card class="chart-card">
                <template #header>
                  <div class="card-header">
                    <span>积分趋势图</span>
                    <el-select v-model="trendTimeRange" @change="loadTrendChart" size="small">
                      <el-option label="最近7天" value="7d" />
                      <el-option label="最近30天" value="30d" />
                      <el-option label="最近3个月" value="3m" />
                    </el-select>
                  </div>
                </template>
                <div ref="trendChartRef" class="chart-container"></div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card class="chart-card">
                <template #header>
                  <div class="card-header">
                    <span>部门积分分布</span>
                  </div>
                </template>
                <div ref="departmentChartRef" class="chart-container"></div>
              </el-card>
            </el-col>
          </el-row>
          
          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="12">
              <el-card class="chart-card">
                <template #header>
                  <div class="card-header">
                    <span>积分类型分布</span>
                  </div>
                </template>
                <div ref="typeChartRef" class="chart-container"></div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card class="chart-card">
                <template #header>
                  <div class="card-header">
                    <span>积分排行榜</span>
                  </div>
                </template>
                <div class="ranking-list">
                  <div
                    v-for="(item, index) in rankingList"
                    :key="index"
                    class="ranking-item"
                  >
                    <div class="rank-number" :class="getRankingClass(index + 1)">
                      {{ index + 1 }}
                    </div>
                    <div class="rank-info">
                      <div class="rank-name">{{ item.userName }}</div>
                      <div class="rank-department">{{ item.departmentName }}</div>
                    </div>
                    <div class="rank-points" :class="item.totalPoints >= 0 ? 'success' : 'danger'">
                      {{ item.totalPoints }}
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 个人详情对话框 -->
    <el-dialog
      v-model="personalDetailVisible"
      title="个人积分详情"
      width="1000px"
    >
      <div v-if="currentPersonalLedger" class="personal-detail">
        <div class="detail-header">
          <h3>{{ currentPersonalLedger.userName }} - 积分明细</h3>
          <div class="detail-summary">
            <el-tag type="info">总积分: {{ currentPersonalLedger.totalPoints }}</el-tag>
            <el-tag type="success">加分: +{{ currentPersonalLedger.addPoints }}</el-tag>
            <el-tag type="danger">扣分: -{{ currentPersonalLedger.deductPoints }}</el-tag>
          </div>
        </div>
        
        <el-table :data="personalRecords" stripe border>
          <el-table-column prop="recordTime" label="时间" width="160" />
          <el-table-column prop="eventDescription" label="事件描述" min-width="200" show-overflow-tooltip />
          <el-table-column prop="pointsType" label="类型" width="80">
            <template #default="{ row }">
              <el-tag :type="row.pointsType === 'add' ? 'success' : 'danger'" size="small">
                {{ row.pointsType === 'add' ? '加分' : '扣分' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="pointsValue" label="分值" width="80">
            <template #default="{ row }">
              <span :class="row.pointsType === 'add' ? 'text-success' : 'text-danger'">
                {{ row.pointsType === 'add' ? '+' : '-' }}{{ row.pointsValue }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)" size="small">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="recorderName" label="记录人" width="100" />
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Download, Document, Refresh, Search, Trophy, Plus, Minus, TrendCharts } from '@element-plus/icons-vue'
import type { PointsLedger, DepartmentPointsSummary, BusinessLinePointsSummary, PointsRecord } from '@/types/points'

// 响应式数据
const personalLoading = ref(false)
const departmentLoading = ref(false)
const userSearchLoading = ref(false)
const activeTab = ref('personal')
const trendTimeRange = ref('7d')

// 数据列表
const personalList = ref<PointsLedger[]>([])
const departmentList = ref<DepartmentPointsSummary[]>([])
const businessList = ref<BusinessLinePointsSummary[]>([])
const users = ref([])
const departments = ref([
  { id: '1', name: '安全部' },
  { id: '2', name: '生产部' },
  { id: '3', name: '技术部' },
  { id: '4', name: '质量部' }
])

// 概览数据
const overview = reactive({
  totalRecords: 156,
  totalAddPoints: 1250,
  totalDeductPoints: 680,
  netPoints: 570,
  pendingApprovals: 8,
  averagePoints: 3.7,
  topDepartment: '安全部'
})

// 搜索表单
const personalSearchForm = reactive({
  userId: '',
  departmentId: '',
  dateRange: []
})

// 分页
const personalPagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 对话框状态
const personalDetailVisible = ref(false)
const currentPersonalLedger = ref<PointsLedger | null>(null)
const personalRecords = ref<PointsRecord[]>([])

// 排行榜数据
const rankingList = ref([
  { userName: '张三', departmentName: '安全部', totalPoints: 45 },
  { userName: '李四', departmentName: '生产部', totalPoints: 38 },
  { userName: '王五', departmentName: '技术部', totalPoints: 32 },
  { userName: '赵六', departmentName: '质量部', totalPoints: 28 },
  { userName: '孙七', departmentName: '安全部', totalPoints: 25 }
])

// 图表引用
const trendChartRef = ref()
const departmentChartRef = ref()
const typeChartRef = ref()

// 模拟数据
const mockPersonalData: PointsLedger[] = [
  {
    id: '1',
    userId: 'u1',
    userName: '张三',
    departmentId: '1',
    departmentName: '安全部',
    totalPoints: 45,
    addPoints: 60,
    deductPoints: 15,
    recordCount: 12,
    lastUpdateTime: '2024-01-15 16:30:00'
  },
  {
    id: '2',
    userId: 'u2',
    userName: '李四',
    departmentId: '2',
    departmentName: '生产部',
    totalPoints: 38,
    addPoints: 50,
    deductPoints: 12,
    recordCount: 10,
    lastUpdateTime: '2024-01-15 15:20:00'
  },
  {
    id: '3',
    userId: 'u3',
    userName: '王五',
    departmentId: '3',
    departmentName: '技术部',
    totalPoints: 32,
    addPoints: 40,
    deductPoints: 8,
    recordCount: 8,
    lastUpdateTime: '2024-01-15 14:10:00'
  }
]

const mockDepartmentData: DepartmentPointsSummary[] = [
  {
    departmentId: '1',
    departmentName: '安全部',
    totalPoints: 156,
    addPoints: 200,
    deductPoints: 44,
    averagePoints: 12.0,
    employeeCount: 13,
    ranking: 1,
    lastUpdateTime: '2024-01-15 16:30:00'
  },
  {
    departmentId: '2',
    departmentName: '生产部',
    totalPoints: 98,
    addPoints: 120,
    deductPoints: 22,
    averagePoints: 8.2,
    employeeCount: 12,
    ranking: 2,
    lastUpdateTime: '2024-01-15 15:20:00'
  },
  {
    departmentId: '3',
    departmentName: '技术部',
    totalPoints: 76,
    addPoints: 90,
    deductPoints: 14,
    averagePoints: 6.3,
    employeeCount: 12,
    ranking: 3,
    lastUpdateTime: '2024-01-15 14:10:00'
  }
]

const mockBusinessData: BusinessLinePointsSummary[] = [
  {
    businessLine: '建筑施工',
    totalPoints: 234,
    addPoints: 280,
    deductPoints: 46,
    averagePoints: 9.4,
    departmentCount: 2,
    ranking: 1,
    lastUpdateTime: '2024-01-15 16:30:00'
  },
  {
    businessLine: '生产制造',
    totalPoints: 156,
    addPoints: 180,
    deductPoints: 24,
    averagePoints: 7.8,
    departmentCount: 2,
    ranking: 2,
    lastUpdateTime: '2024-01-15 15:20:00'
  }
]

// 方法
const loadData = async () => {
  await Promise.all([
    loadPersonalData(),
    loadDepartmentData(),
    loadBusinessData(),
    loadCharts()
  ])
}

const loadPersonalData = async () => {
  personalLoading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    personalList.value = mockPersonalData
    personalPagination.total = mockPersonalData.length
  } catch (error) {
    ElMessage.error('加载个人数据失败')
  } finally {
    personalLoading.value = false
  }
}

const loadDepartmentData = async () => {
  departmentLoading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    departmentList.value = mockDepartmentData
  } catch (error) {
    ElMessage.error('加载部门数据失败')
  } finally {
    departmentLoading.value = false
  }
}

const loadBusinessData = async () => {
  businessLoading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    businessList.value = mockBusinessData
  } catch (error) {
    ElMessage.error('加载业务线数据失败')
  } finally {
    businessLoading.value = false
  }
}

const loadCharts = async () => {
  await nextTick()
  // 这里可以集成 ECharts 或其他图表库
  // 暂时用模拟数据
}

const loadTrendChart = () => {
  // 重新加载趋势图
  loadCharts()
}

const handleTabChange = (tab: string) => {
  activeTab.value = tab
  if (tab === 'charts') {
    nextTick(() => {
      loadCharts()
    })
  }
}

const resetPersonalSearch = () => {
  Object.assign(personalSearchForm, {
    userId: '',
    departmentId: '',
    dateRange: []
  })
  loadPersonalData()
}

const handlePersonalSizeChange = (size: number) => {
  personalPagination.pageSize = size
  personalPagination.page = 1
  loadPersonalData()
}

const handlePersonalCurrentChange = (page: number) => {
  personalPagination.page = page
  loadPersonalData()
}

const searchUsers = async (query: string) => {
  if (!query) return
  userSearchLoading.value = true
  try {
    // 模拟用户搜索
    await new Promise(resolve => setTimeout(resolve, 300))
    users.value = [
      { id: 'u1', name: '张三' },
      { id: 'u2', name: '李四' },
      { id: 'u3', name: '王五' }
    ].filter(user => user.name.includes(query))
  } catch (error) {
    ElMessage.error('搜索用户失败')
  } finally {
    userSearchLoading.value = false
  }
}

const viewPersonalDetail = (row: PointsLedger) => {
  currentPersonalLedger.value = row
  // 模拟加载个人记录
  personalRecords.value = [
    {
      id: '1',
      departmentId: row.departmentId,
      departmentName: row.departmentName,
      responsiblePersonId: row.userId,
      responsiblePersonName: row.userName,
      eventDescription: '主动发现安全隐患',
      pointsType: 'add',
      pointsValue: 10,
      attachments: [],
      recorderId: 'u2',
      recorderName: '李四',
      recordTime: '2024-01-15 09:30:00',
      status: 'approved'
    }
  ]
  personalDetailVisible.value = true
}

const viewDepartmentDetail = (row: DepartmentPointsSummary) => {
  ElMessage.info('部门详情功能开发中...')
}

const viewBusinessDetail = (row: BusinessLinePointsSummary) => {
  ElMessage.info('业务线详情功能开发中...')
}

const exportReport = async (format: 'excel' | 'pdf') => {
  try {
    ElMessage.success(`正在导出${format.toUpperCase()}报表...`)
    // 模拟导出
    await new Promise(resolve => setTimeout(resolve, 2000))
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 工具方法
const getRankingType = (rank: number) => {
  if (rank === 1) return 'danger'
  if (rank === 2) return 'warning'
  if (rank === 3) return 'success'
  return 'info'
}

const getRankingClass = (rank: number) => {
  if (rank === 1) return 'first'
  if (rank === 2) return 'second'
  if (rank === 3) return 'third'
  return ''
}

const getStatusType = (status: string) => {
  const statusMap = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger',
    cancelled: 'info'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const statusMap = {
    pending: '待审批',
    approved: '已通过',
    rejected: '已拒绝',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.points-ledger {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #303133;
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .overview-cards {
    margin-bottom: 20px;
    
    .overview-card {
      .card-content {
        display: flex;
        align-items: center;
        
        .card-icon {
          width: 60px;
          height: 60px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 16px;
          
          .el-icon {
            font-size: 24px;
            color: #fff;
          }
          
          &.total {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          }
          
          &.add {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
          }
          
          &.deduct {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
          }
          
          &.net {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
          }
        }
        
        .card-info {
          flex: 1;
          
          .card-title {
            font-size: 14px;
            color: #909399;
            margin-bottom: 8px;
          }
          
          .card-value {
            font-size: 24px;
            font-weight: bold;
            color: #303133;
            
            &.success {
              color: #67c23a;
            }
            
            &.danger {
              color: #f56c6c;
            }
          }
        }
      }
    }
  }
  
  .tab-content {
    .search-form {
      background: #fff;
      padding: 20px;
      border-radius: 8px;
      margin-bottom: 20px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
    
    .table-container {
      background: #fff;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      
      .pagination-container {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
      }
    }
    
    .chart-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      
      .chart-container {
        height: 300px;
        width: 100%;
      }
      
      .ranking-list {
        .ranking-item {
          display: flex;
          align-items: center;
          padding: 12px 0;
          border-bottom: 1px solid #f0f0f0;
          
          &:last-child {
            border-bottom: none;
          }
          
          .rank-number {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            color: #fff;
            margin-right: 12px;
            
            &.first {
              background: #ffd700;
            }
            
            &.second {
              background: #c0c0c0;
            }
            
            &.third {
              background: #cd7f32;
            }
            
            &:not(.first):not(.second):not(.third) {
              background: #909399;
            }
          }
          
          .rank-info {
            flex: 1;
            
            .rank-name {
              font-weight: 500;
              color: #303133;
            }
            
            .rank-department {
              font-size: 12px;
              color: #909399;
            }
          }
          
          .rank-points {
            font-weight: bold;
            font-size: 16px;
            
            &.success {
              color: #67c23a;
            }
            
            &.danger {
              color: #f56c6c;
            }
          }
        }
      }
    }
  }
  
  .text-success {
    color: #67c23a;
    font-weight: bold;
  }
  
  .text-danger {
    color: #f56c6c;
    font-weight: bold;
  }
  
  .personal-detail {
    .detail-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      h3 {
        margin: 0;
        color: #303133;
      }
      
      .detail-summary {
        display: flex;
        gap: 8px;
      }
    }
  }
}
</style>
